import threading
import random
import time
gCondition = threading.Condition()
gMoney = 1000
gTotalTime = 10
gTime = 0 #生产一次 次数+1 消费一次 都加1
#生产者
class ProducerThread(threading.Thread):
    def run(self):
        global gMoney
        global gTime
        while True:
            money = random.randint(100,999)
            gCondition.acquire()

            if gTime >= gTotalTime:
                gCondition.release()
                break
            gMoney += money
            print("%s生产了%d元钱,余额为%d元钱" % (threading.current_thread(),money,gMoney))
            gTime += 1
            gCondition.notify_all() #通知所有正在等待的进程
            gCondition.release()
            time.sleep(1)

#消费者
class CustomerThread(threading.Thread):
    def run(self):
        global gMoney
        while True:
            money = random.randint(100,999)
            gCondition.acquire()
            #if 判断完了以后会执行下面的语句
            #while挑战执行完了以后还要回来再判断一次
            while gMoney < money: #用while 避免了 等待以后 去消费 发现还是余额不足
                if gTime >= gTotalTime:
                    gCondition.release()
                    return  #用return 替代break   return返回所有
                print("%s准备消费%d元钱,余额为%d元钱 余额不足" % (threading.current_thread(), money, gMoney))
                gCondition.wait() #等待notify_all 的通知

            gMoney -= money
            print("%s消费%d元钱,余额为%d元钱" % (threading.current_thread(), money, gMoney))
            gCondition.release()
            time.sleep(1)

def main():
    for x in range(3):
        t = CustomerThread()
        t.start()
    for x in range(5):
        t = ProducerThread()
        t.start()

if __name__ == '__main__':
    main()